﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Web.Security;
using TTJ.DataModel;

namespace TTJ.Service
{
    public static class TranslateHelper
    {

        public static string get_uft8(string unicodeString)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            Byte[] encodedBytes = utf8.GetBytes(unicodeString);
            String decodedString = utf8.GetString(encodedBytes);
            return decodedString;
        }

        public static string MD5Encrypt32(string password)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5").ToLower();
        }

        public static string getTranslatedKeyword(string keyword)
        {
            if (string.IsNullOrEmpty(keyword)) return "";
            string q = get_uft8(keyword);

            string TranslateApiId = System.Configuration.ConfigurationManager.AppSettings["TranslateApiId"];
            string TranslateKey = System.Configuration.ConfigurationManager.AppSettings["TranslateKey"];
            string Url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            string jsonResult = "";
            Random r = new Random();
            int salt = r.Next();
            string sign = MD5Encrypt32(TranslateApiId + q + salt + TranslateKey);
            Url += "q=" + keyword + "&from=ch&to=en&appid=" + TranslateApiId + "&salt=" + salt + "&sign=" + sign;
            try
            {
                HttpWebRequest getAccessRequest = WebRequest.Create(Url) as HttpWebRequest;
                //getAccessRequest.Proxy = null;
                getAccessRequest.ContentType = "multipart/form-data";
                getAccessRequest.Timeout = 30000;//30秒连接不成功就中断 
                getAccessRequest.Method = "post";

                HttpWebResponse response = getAccessRequest.GetResponse() as HttpWebResponse;
                using (StreamReader strHttpComback = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    jsonResult = strHttpComback.ReadToEnd();
                }
            }
            catch (Exception ex)
            {

            }


            //解析json  
            JavaScriptSerializer jss = new JavaScriptSerializer();
            TranslationResult result = jss.Deserialize<TranslationResult>(jsonResult);
            if (result.Error_code == null) return result.Trans_result[0].Dst;
            return "";
        }
    }
}
